<template>
    <div class="auth-container">
      <el-card class="auth-card">
        <h2>登录塔罗</h2>
        <el-form
          :model="form"
          :rules="rules"
          @submit.prevent="handleLogin"
        >
          <el-form-item prop="username">
            <el-input
              v-model="form.username"
              placeholder="用户名"
              prefix-icon="User"
            />
          </el-form-item>

          <el-form-item prop="password">
            <el-input
              v-model="form.password"
              type="password"
              placeholder="密码"
              prefix-icon="Lock"
              show-password
            />
          </el-form-item>

          <el-form-item>
            <el-button
              type="primary"
              native-type="submit"
              class="full-width"
            >
              登录
            </el-button>
          </el-form-item>

          <div class="auth-footer">
            没有账号？<router-link to="/register">立即注册</router-link>
          </div>
        </el-form>
      </el-card>
    </div>
  </template>

  <script setup >

  import { ref } from 'vue'
  import router from '@/router'
  import axios from 'axios'
  import { ElMessage } from 'element-plus'
  import { login } from '@/services/api';
  const form = ref({ username: '', password: '' })
  const rules = {
    username: [
      { required: true, message: '请输入用户名', trigger: 'blur' },
      { min: 4, max: 16, message: '长度在4到16个字符', trigger: 'blur' }
    ],
    password: [
      { required: true, message: '请输入密码', trigger: 'blur' },
      { min: 6, message: '密码长度至少6位', trigger: 'blur' }
    ]
  }
  const handleLogin = async () => {
  try {
    const response = await login(form.value);
    if (response.data.success) {
      ElMessage.success('登录成功');
      localStorage.setItem('token', response.data.data.token); // 保存 token
      console.log(response.data.data.token);
      router.push('/home'); // 使用路由实例的 push 方法
    } else {
      ElMessage.error(response.data.message);
    }
  } catch (error) {
    ElMessage.error('登录失败，请检查用户名和密码');
    console.error(error);
  }
};
  </script>

  <style scoped>
  .auth-container {
    display: flex;
    justify-content: center;
    align-items: center;
    height: 100vh;
    background: #f0f2f5;
  }

  .auth-card {
    width: 400px;
    padding: 24px;
  }

  h2 {
    text-align: center;
    margin-bottom: 24px;
  }

  .full-width {
    width: 100%;
  }

  .auth-footer {
    text-align: center;
    margin-top: 16px;
    color: #606266;
  }
  </style>